<?php
namespace Cyfy\Modules\Book\Forms;

use \Cyfy\Modules\Forms;
use \Cyfy\Modules\Users\Current;
use \Cyfy\Modules\Book\Module;

/**
 * Creating new entry form.
 * 
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */
class NewEntry extends Forms\Form
{
    /**
     * Structure of the form.
     */
    public function structure()
    {
        $this -> onSubmit = "Cyfy.ajax('Book', 'entries', '#guestBook', ''); $('.bookNewEntryCollapsibleForm').slideUp('fast');";
        $this -> permission("Book", "add new");
        
        // If user not logged, show input name
        if(Current :: $uid == 0)
        {
            $i = new Forms\TextBox("name", Module ::t(110));
            $i -> maxlength = 255;
            $i -> required = true;
            $this -> addItem($i);
        }
        
        // if title
        if(Module ::constant('showTitle'))
        {
            $i = new Forms\TextBox("title", Module ::t(120));
            $i -> maxlength = 255;
            $i -> required = true;
            $this -> addItem($i);
        }

        $i = new Forms\TextArea("text",  Module ::t(130));
        $i -> required = true;
        $this -> addItem($i);
        
        $b = new Forms\Button(Module :: t(140));
        $this -> addButton($b);
        
    }
   
    /**
     * Submitting
     */
    public function submit()
    {
        $values = $this -> getAll();
        $values["language"] = \Cyfy\Language :: getActive();
        $values["time"] = new \DateTime();
        $values["text"] = textWithLinks(nl2br($values["text"]));
        $values["uid"] = \Cyfy\Modules\Users\Current :: $uid;
        
        if(\dibi :: query("INSERT INTO [:cyfy:Book]", $values))
        {
            \Cyfy\Message :: set(Module :: t(101, array($this -> get("title"))));
        }
        else
        {
            \Cyfy\Message :: set(Module :: t(102, array($this -> get("title"))), \Cyfy\Message::ERROR);
        }
        return true;
    }
}